package com.ant.backstage.service.common;

import com.ant.backstage.facade.model.ActivitySuccessLog;
import com.ant.backstage.service.ActivitySuccessLogService;
import com.ant.backstage.service.GoodsService;
import com.ant.backstage.utils.ioc.ApplicationContextUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.LinkedBlockingDeque;


public class SpikeGoodsQueueThread implements Runnable  {

    private static Logger logger = LogManager.getLogger(SpikeGoodsQueueThread.class);

    private final LinkedBlockingDeque<ActivitySuccessLog> deque;

    public SpikeGoodsQueueThread(LinkedBlockingDeque<ActivitySuccessLog> deque) {
        this.deque = deque;
    }

    @Override
    public void run() {
        logger.info("秒杀成功，处理队列数据，开始");
        try {
            //开始处理请求队列中的请求,按照队列的FIFO的规则,先处理先放入到队列中的请求
            ActivitySuccessLogService activitySuccessLogService = ApplicationContextUtil.getBean(ActivitySuccessLogService.class);
            GoodsService goodsService = ApplicationContextUtil.getBean(GoodsService.class);
            while (deque != null && deque.size() > 0){
                ActivitySuccessLog suLog = deque.take();//取出队列中的请求
                //业务逻辑
                // 1. 秒杀成功持久化
                synchronized (suLog){
                    //成功记录
                    int insert = activitySuccessLogService.insert(suLog);

                    //生成订单  略

                    //减数据库 商品库存
                    goodsService.updateGoodsStock(suLog.getGoodsScn(),"-1");
                }


                logger.info("秒杀成功，处理队列数据 结束");
            }
        }catch (Exception e){
            logger.error("【SpikeGoodsQueueThread】秒杀成功队列数据异常");
            e.printStackTrace();
        }
    }
}
